//
//  XHWithdrawalViewController.m
//  umibus
//
//  Created by 冷山 on 16/6/16.
//  Copyright © 2016年 lexingsoft. All rights reserved.
//

#import "XHWithdrawalViewController.h"
#import "XHWithdrawalSubsidiaryViewController.h"
#import "XHBankCardPickerViewController.h"

#import "XHMyMoneyCell.h"
#import "XHBalanceInfoCell.h"
#import "XHPayTreasureCell.h"
#import "XHBankCardCell.h"
#import "XHToConfirmWithdrawalCell.h"

#import "Services.h"
#import "XHMyTemplateManager.h"

#define kNameTextFieldTag 100
#define kAccountTextFieldTag 101

#define kBankNameTextFieldTag 10
#define kCardNumberTextFieldTag 103
#define kBankTextFieldTag 104

@interface XHWithdrawalViewController ()<XHBankCardCellDelegate,XHToConfirmWithdrawalCellDelegate,XHBankCardPickerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *ui_tableView;
@property (strong, nonatomic) NSString *selectedSubject;
@property (strong, nonatomic) NSDictionary *m_infoDic;
@property (assign, nonatomic) NSInteger money;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *la_bottomViewBottomConstraint;

@property (strong, nonatomic) NSString *m_name;
@property (strong, nonatomic) NSString *m_account;

@property (strong, nonatomic) NSString *m_bankAccount;
@property (strong, nonatomic) NSString *m_cardNumber;
@property (strong, nonatomic) NSString *m_bankName;

@property (strong, nonatomic) NSDictionary * m_bankDic;
@property (strong, nonatomic) NSMutableArray *m_mutableArray1;
@property (strong, nonatomic) NSMutableArray *m_mutableArray;

@end

@implementation XHWithdrawalViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
    [self.ui_tableView registerNib:[UINib nibWithNibName:@"XHMyMoneyCell" bundle:nil] forCellReuseIdentifier:XHMyMoneyCellIdentifier];
    [self.ui_tableView registerNib:[UINib nibWithNibName:@"XHBalanceInfoCell" bundle:nil] forCellReuseIdentifier:XHBalanceInfoCellIdentifier];
    [self.ui_tableView registerNib:[UINib nibWithNibName:@"XHBankCardCell" bundle:nil] forCellReuseIdentifier:XHBankCardCellIdentifier];
    [self.ui_tableView registerNib:[UINib nibWithNibName:@"XHPayTreasureCell" bundle:nil] forCellReuseIdentifier:XHPayTreasureCellIdentifier];
    [self.ui_tableView registerNib:[UINib nibWithNibName:@"XHToConfirmWithdrawalCell" bundle:nil] forCellReuseIdentifier:XHToConfirmWithdrawalCellIdentifier];
    
    UIBarButtonItem *settingItem=[[UIBarButtonItem alloc] initWithTitle:@"提现明细" style:UIBarButtonItemStylePlain target:self action:@selector(settingAction:)];
    self.navigationItem.rightBarButtonItem=settingItem;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShowNotification:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideNotification:) name:UIKeyboardWillHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self getUserInfo];
    [self getUserBankOrAlipay];
}

//从缓存中取出上次成功提现的帐号
- (void)getUserBankOrAlipay
{
    NSUserDefaults * userDefaultsArr = [NSUserDefaults standardUserDefaults];
    self.m_mutableArray = [userDefaultsArr objectForKey:@"alipay"];
    self.m_mutableArray1= [userDefaultsArr objectForKey:@"bank"];
    //每次进入取一次缓存
    NSDictionary * dic = self.m_mutableArray.firstObject;
    NSDictionary * dic1 = self.m_mutableArray1.firstObject;
    
    self.m_name = [NSString stringWithFormat:@"%@",dic[@"alipayName"]];
    self.m_account = [NSString stringWithFormat:@"%@",dic[@"alipayAccount"]];
    
    self.m_bankAccount = [NSString stringWithFormat:@"%@",dic1[@"bankAccount"]];
    self.m_cardNumber = [NSString stringWithFormat:@"%@",dic1[@"bankCard"]];
    self.m_bankName = [NSString stringWithFormat:@"%@",dic1[@"bankName"]];
}


- (void)getUserInfo
{
    if ([[DataManager sharedInstance] isLogin])
    {
        self.m_infoDic=[ServiceManager getUserInfoSuccess:^(NSDictionary *data) {
            self.m_infoDic = data;
            self.money = [[NSString stringWithFormat:@"%@",self.m_infoDic[@"cashoutBalance"]] integerValue];
            [self.ui_tableView reloadData];
        } failure:^{
            
        }];
        self.money = [[NSString stringWithFormat:@"%@",self.m_infoDic[@"cashoutBalance"]] integerValue];
        [self.ui_tableView reloadData];
    }
}

- (void)settingAction:(UIButton*)button
{
    XHWithdrawalSubsidiaryViewController * viewController = [[XHWithdrawalSubsidiaryViewController alloc]init];
    viewController.title = @"提现明细";
    [self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSUInteger rows=1;
    if (section==2)
    {
        rows = 3;
    }
    return rows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    if(indexPath.section==0)
    {
        cell = [self myMoneyCell:indexPath];
    }
    else if (indexPath.section==1)
    {
        cell = [self balanceInfoCell:indexPath];
    }
    else if (indexPath.section==2)
    {
        if (indexPath.row == 0)
        {
            cell = [self payTreasureCell];
        }
        else if (indexPath.row == 1)
        {
            cell = [self bankCardCell];
        }
        else if (indexPath.row==2)
        {
            cell = [self toConfirmWithdrawalCell];
        }
    }
    return cell;
}

- (XHMyMoneyCell*)myMoneyCell:(NSIndexPath*)indexPath
{
    XHMyMoneyCell * cell = [self.ui_tableView dequeueReusableCellWithIdentifier:XHMyMoneyCellIdentifier];
    
    cell.ui_money.text = [NSString stringWithFormat:@"%.2f",[self.m_infoDic[@"cashoutBalance"] doubleValue]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (XHBalanceInfoCell*)balanceInfoCell:(NSIndexPath*)indexPath
{
    XHBalanceInfoCell * cell = [self.ui_tableView dequeueReusableCellWithIdentifier:XHBalanceInfoCellIdentifier];
    cell.ui_historyTotal.text = [NSString stringWithFormat:@"%.2f",[self.m_infoDic[@"cumulativeBalance"] doubleValue]];
    cell.ui_theAccount.text = [NSString stringWithFormat:@"%.2f",[self.m_infoDic[@"applingOutBalance"] doubleValue]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (XHPayTreasureCell *)payTreasureCell
{
    XHPayTreasureCell *cell = [self.ui_tableView dequeueReusableCellWithIdentifier:XHPayTreasureCellIdentifier];
    cell.layer.masksToBounds=YES;
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.ui_jianTouBtn.selected = self.selectedSubject==kPayTreasureWithdrawal;
    cell.ui_nameText.tag = kNameTextFieldTag;
    cell.ui_accountText.tag = kAccountTextFieldTag;
    if([NSString checkNullString:self.m_name])
    {
        cell.ui_nameText.text = @"";
    }
    else
    {
        cell.ui_nameText.text = [NSString stringWithFormat:@"%@",self.m_name];
    }
    
    if([NSString checkNullString:self.m_account])
    {
        cell.ui_nameText.text = @"";
    }
    else
    {
        cell.ui_accountText.text = [NSString stringWithFormat:@"%@",self.m_account];
    }

    
    return cell;
}

- (XHBankCardCell *)bankCardCell
{
    XHBankCardCell *cell = [self.ui_tableView dequeueReusableCellWithIdentifier:XHBankCardCellIdentifier];
    cell.delegate = self;
    cell.layer.masksToBounds=YES;
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.ui_jianTouBtn.selected=self.selectedSubject==kBankCardWithdrawal;
    cell.ui_bankNameText.tag = kBankNameTextFieldTag;
    cell.ui_cardNumber.tag = kCardNumberTextFieldTag;
    if([NSString checkNullString:self.m_bankAccount])
    {
        cell.ui_bankNameText.text = @"";
    }
    else
    {
        cell.ui_bankNameText.text = [NSString stringWithFormat:@"%@",self.m_bankAccount];
    }
    if([NSString checkNullString:self.m_cardNumber])
    {
        cell.ui_cardNumber.text = @"";
    }
    else
    {
        cell.ui_cardNumber.text = [NSString stringWithFormat:@"%@",self.m_cardNumber];
    }
    if([NSString checkNullString:self.m_bankName])
    {
        cell.ui_bankLabel.text = @"请输入您的银行卡开户银行";
    }
    else
    {
        cell.ui_bankLabel.text = [NSString stringWithFormat:@"%@",self.m_bankName];
    }
    
    if (self.m_bankDic)
    {
        NSString * bank = self.m_bankDic[@"dictDataValue"];
        cell.ui_bankLabel.textColor = [ColorManager colorWithHexString:@"#000000" alpha:0.8];
        cell.ui_bankLabel.text = bank;
    }
    else
    {
        cell.ui_bankLabel.textColor = [ColorManager colorWithHexString:@"#000000" alpha:0.25];
    }
    if([NSString checkNullString:self.m_bankName]&&!self.m_bankDic)
    {
        cell.ui_bankLabel.textColor = [ColorManager colorWithHexString:@"#000000" alpha:0.25];
    }
    else
    {
        cell.ui_bankLabel.textColor = [ColorManager colorWithHexString:@"#000000" alpha:0.8];
    }

    return cell;
}

- (XHToConfirmWithdrawalCell*)toConfirmWithdrawalCell
{
    XHToConfirmWithdrawalCell * cell = [self.ui_tableView dequeueReusableCellWithIdentifier:XHToConfirmWithdrawalCellIdentifier];
    cell.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (![NSString checkNullString:self.m_name]&&
        ![NSString checkNullString:self.m_account])
    {
        cell.ui_withdrawalBtn.backgroundColor = [ColorManager colorWithHexString:@"#5997A4" alpha:1];
        cell.ui_withdrawalBtn.enabled = YES;
    }
    else if (![NSString checkNullString:self.m_bankAccount]&&
             ![NSString checkNullString:self.m_cardNumber]&&
             ![NSString checkNullString:self.m_bankName])
    {
        cell.ui_withdrawalBtn.backgroundColor = [ColorManager colorWithHexString:@"#5997A4" alpha:1];
        cell.ui_withdrawalBtn.enabled = YES;
    }
    else
    {
        cell.ui_withdrawalBtn.backgroundColor = [ColorManager colorWithHexString:@"#000000" alpha:0.25];
        cell.ui_withdrawalBtn.enabled = NO;
    }

    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==2)
    {
        if (indexPath.row == 0)
        {
            self.selectedSubject = kPayTreasureWithdrawal;
            NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:2];
            XHPayTreasureCell * cell = [self.ui_tableView cellForRowAtIndexPath:indexPath];
            
            NSIndexPath * indexPath1 = [NSIndexPath indexPathForRow:1 inSection:2];
            XHBankCardCell * cell1 = [self.ui_tableView cellForRowAtIndexPath:indexPath1];
            
            [cell.ui_jianTouBtn setSelected:YES];
            [cell1.ui_jianTouBtn setSelected:NO];
            
            [tableView beginUpdates];
            [tableView endUpdates];
        }
        else if (indexPath.row == 1)
        {
            self.selectedSubject = kBankCardWithdrawal;
            NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:2];
            XHPayTreasureCell * cell = [self.ui_tableView cellForRowAtIndexPath:indexPath];
            
            NSIndexPath * indexPath1 = [NSIndexPath indexPathForRow:1 inSection:2];
            XHBankCardCell * cell1 = [self.ui_tableView cellForRowAtIndexPath:indexPath1];
            
            [cell.ui_jianTouBtn setSelected:NO];
            [cell1.ui_jianTouBtn setSelected:YES];
            
            [tableView beginUpdates];
            [tableView endUpdates];
        }
    }
}

- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    CGFloat height = 0.1;
    return height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
{
    CGFloat height = 10;
    return height;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height=0;
    if (indexPath.section == 0)
    {
        height = 108;
    }
    else if (indexPath.section==1)
    {
        height = 65;
    }
    else if (indexPath.section==2)
    {
        if (indexPath.row == 0)
        {
            if (self.selectedSubject==kPayTreasureWithdrawal)
            {
                height = 190;
            }
            else
            {
                height = 100;
            }
        }
        else
        {
            height = 100;
        }
        if (indexPath.row == 1)
        {
            if (self.selectedSubject==kBankCardWithdrawal)
            {
                height = 195;
            }
            else
            {
                height = 60;
            }
        }
        if (indexPath.row ==2)
        {
            height = 110;
        }
    }
    
    return height;
}

#pragma mark - TextFieldNotification

- (void)textFieldTextDidChangeNotification:(NSNotification *)notif
{
    UITextField * textField = (UITextField *)[notif object];
    switch (textField.tag)
    {
        case kNameTextFieldTag:
            self.m_name = textField.text;
            break;
        case kAccountTextFieldTag:
            self.m_account = textField.text;
            break;
        case kBankNameTextFieldTag:
            self.m_bankAccount = textField.text;
            break;
        case kCardNumberTextFieldTag:
            self.m_cardNumber = textField.text;
            break;
    }
    if (![NSString checkNullString:self.m_name]&&
        ![NSString checkNullString:self.m_account])
    {
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:2 inSection:2];
        [self.ui_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    }
    else if (![NSString checkNullString:self.m_bankAccount]&&
             ![NSString checkNullString:self.m_cardNumber]&&
             ![NSString checkNullString:self.m_bankDic[@"dictDataValue"]])
        
    {
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:2 inSection:2];
        [self.ui_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    }
    else
    {
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:2 inSection:2];
        [self.ui_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    }
}


#pragma mark - KeyBoardNotification

- (void)keyboardWillShowNotification:(NSNotification *)notif{
    float animationTime=[[notif.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGFloat keyboardHeight=[notif.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    WS(weakSelf)
    [UIView animateWithDuration:animationTime animations:^{
        CGFloat constant=weakSelf.la_bottomViewBottomConstraint.constant;
        weakSelf.la_bottomViewBottomConstraint.constant=keyboardHeight > constant ? keyboardHeight : constant;
        [weakSelf.view layoutIfNeeded];
    }];
}

- (void)keyboardWillHideNotification:(NSNotification *)notif{
    float animationTime=[[notif.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    WS(weakSelf)
    [UIView animateWithDuration:animationTime animations:^{
        weakSelf.la_bottomViewBottomConstraint.constant=0;
        [weakSelf.view layoutIfNeeded];
    }];
}

#pragma XHBankCardCellDelegate

- (void)selectBank
{
    XHBankCardPickerViewController *viewController=[[XHBankCardPickerViewController alloc] init];
    viewController.delegate=self;
    viewController.modalPresentationStyle=UIModalPresentationCustom;
    [self presentViewController:viewController animated:NO completion:nil];
}


#pragma - mark 提现

///提现
- (void)withdrawalAction:(UIButton*)btn
{
    if (self.selectedSubject==kPayTreasureWithdrawal)
    {
        
        if ([NSString checkNullString:self.m_name])
        {
            [PromptAction showInfoPrompt:@"姓名不能为空"];
        }
        else if ([NSString checkNullString:self.m_account])
        {
            [PromptAction showInfoPrompt:@"支付宝帐号不能为空"];
        }
        else if ([NSString checkNullString:self.m_name]&&
                 [NSString checkNullString:self.m_account])
        {
            [PromptAction showInfoPrompt:@"提现信息不能为空"];
        }
        else
        {
            btn.enabled = NO;
            NSLog(@"%@ %@ %@",self.m_infoDic[@"cashoutBalance"],self.m_name,self.m_account);
            [ServiceManager postUserWithdrawalWithApplayType:@"alipay" transferAccount:self.m_account transferName:self.m_name outAmount:self.m_infoDic[@"cashoutBalance"] openBank:@"" success:^(NSDictionary *data) {
                [PromptAction showSuccessPrompt:@"申请提现成功！后台核对信息后将一周内完成转账"];
                NSDictionary * dic = @{@"alipayName":self.m_name,
                                       @"alipayAccount":self.m_account};
                
                [XHMyTemplateManager addTemlpate:dic sequenceNBR:@"alipay"];
                btn.enabled = YES;
                XHWithdrawalSubsidiaryViewController * viewController = [[XHWithdrawalSubsidiaryViewController alloc]init];
                viewController.title = @"提现明细";
                [self.navigationController pushViewController:viewController animated:YES];
            } failure:^(NSDictionary *data) {
                btn.enabled = YES;
            }];
        }
    }
    else if (self.selectedSubject==kBankCardWithdrawal)
    {
        NSLog(@"%@ %@ %@",self.m_infoDic[@"cashoutBalance"],self.m_bankAccount,self.m_cardNumber);
        if ([NSString checkNullString:self.m_bankAccount])
        {
            [PromptAction showInfoPrompt:@"姓名不能为空"];
        }
        else if ([NSString checkNullString:self.m_cardNumber])
        {
            [PromptAction showInfoPrompt:@"卡号不能为空"];
        }
        else if ([NSString checkNullString:self.m_bankName])
        {
            [PromptAction showInfoPrompt:@"开户行不能为空"];
        }
        else if ([NSString checkNullString:self.m_bankAccount]&&
                 [NSString checkNullString:self.m_cardNumber])
        {
            [PromptAction showInfoPrompt:@"提现信息不能为空"];
        }
        else
        {
            btn.enabled = NO;
            if((self.m_cardNumber.length>19 || self.m_cardNumber.length==19)&&
               (self.m_cardNumber.length<24 || self.m_cardNumber.length==24))
            {
                NSLog(@"%ld",self.m_cardNumber.length);
                [ServiceManager postUserWithdrawalWithApplayType:@"bank" transferAccount:self.m_cardNumber transferName:self.m_bankAccount outAmount:self.m_infoDic[@"cashoutBalance"] openBank:self.m_bankName success:^(NSDictionary *data) {
                    [PromptAction showSuccessPrompt:@"申请提现成功！后台核对信息后将一周内完成转账"];
                    NSDictionary * dic = @{@"bankAccount":self.m_bankAccount,
                                           @"bankCard":self.m_cardNumber,
                                           @"bankName":self.m_bankName};
                    btn.enabled = YES;
                    [XHMyTemplateManager addTemlpate:dic sequenceNBR:@"bank"];
                    XHWithdrawalSubsidiaryViewController * viewController = [[XHWithdrawalSubsidiaryViewController alloc]init];
                    viewController.title = @"提现明细";
                    [self.navigationController pushViewController:viewController animated:YES];
                } failure:^(NSDictionary *data) {
                    btn.enabled = YES;
                }];
            }
            else
            {
                [PromptAction showInfoPrompt:@"银行卡号格式不正确"];
                btn.enabled = YES;
            }
        }
    }
    else
    {
        [PromptAction showInfoPrompt:@"请选择提现方式"];
    }
}

#pragma mark - XHBankCardPickerViewDelegate

- (void)didSelectedBankDictionary:(NSDictionary *)bankDic
{
    if (bankDic)
    {
        self.m_bankDic=bankDic;
        self.m_bankName = self.m_bankDic[@"dictDataValue"];
        [self.ui_tableView reloadData];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
